1.3 - C# If statements
What are If statments?
An if statement basically let execute the code only if the condition is met.
So for example if we would like to change the player speed only when our stamina is below 25
we would need an if statement to check if our stamina is below 25.
If it is, the code that changes the player speed will be executed, else it won't.
protected override void OnGameStart()
{
if (LocalPlayer.Vitals.GetStamina() < 25) // checking if the player stamina is below 25
{
// setting the player walk and run speed if the above condition is met
LocalPlayer.FpCharacter.SetWalkSpeed(10);
LocalPlayer.FpCharacter.SetRunSpeed(20);
}
// if the condition isn't met the code will continue from this line
}
Checking multiple conditions
In some cases we may need to check multiple conditions to let our code execute.
To do that we have two operators:
- Two ampersands: &&
- Two vertical bars: ||
What's the difference?
We can translate the &&
as "if first condition and second condition are met,
then execute the code in curly braces".
On the other way, we can translate the ||
as "if first condition or
second condition is met, then execute the code in curly braces. "
// Ampersands example
protected override void OnGameStart()
{
if (LocalPlayer.Vitals.GetStamina() < 25 && LocalPlayer.Vitals.GetHealth() > 70) // checking if the player stamina is below 25 AND the player health is above 70
{
// setting the player walk and run speed if the above conditions are met
LocalPlayer.FpCharacter.SetWalkSpeed(10);
LocalPlayer.FpCharacter.SetRunSpeed(20);
}
// if the conditions aren't met the code will continue from this line
}
// Vertical bars example
protected override void OnGameStart()
{
if (LocalPlayer.Vitals.GetStamina() < 25 || LocalPlayer.Vitals.GetHealth() > 70) // checking if the player stamina is below 25 OR the player health is above 70
{
// setting the player walk and run speed if atleast one of the above conditions is met
LocalPlayer.FpCharacter.SetWalkSpeed(10);
LocalPlayer.FpCharacter.SetRunSpeed(20);
}
// if none of the conditions is met the code will continue from this line
}